<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\goods\LihuaStock;
use app\common\model\LihuaOrder;
use app\common\model\LihuaRefund; //退单记录
use app\common\model\LihuaOrderGoods;
use app\common\model\LihuaUserbonus;
use app\common\model\LihuaHongbao;
use app\common\model\LihuaActivity; //城市活动表
use app\common\model\LihuaOrderActivity; //订单活动表
use app\common\model\LihuaVouchers; //现金抵用券
use app\common\model\LihuaOrderLogistics;
use app\admin\model\User;
use app\common\model\general\LihuaStore;
use app\common\model\goods\LihuaGoods;
use fast\Http;
use think\Db;
use think\Exception;
use think\Validate;
use think\Log;

/**
 * 写字楼项目相关接口
 */
class Office extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /***
     * 根据经纬度获取所在位置城市所有运营中的写字楼
     * 更具和当前位置的距离进行排序
     * */
    public function list(){
        $lng = $this->request->request('lng', 0); //经度
        $lat = $this->request->request('lat', 0); //纬度
        $city_id = $this->request->request('city_id', 0); //城市ID
        if (!$lng || !$lat || !$city_id) $this->error('参数错误');
        /**
         * 获取某城市下的所有写字楼项目
         * 通过HTTP接口获取私定系统的写字楼列表信息
         * */
        $api = "https://private.lihua.com/api/office/list?city_id=".$city_id."&lng=".$lng."&lat=".$lat;
        $res = Http::get($api);
        $ret = json_decode($res, true);
        $data = $ret['data'];
        $this->success('OK', [$data, count($data)]);
    }

    public function store() {
        $store_name  = $this->request->request('store_name', '');
        $city_id    = $this->request->request('city_id', 0);
        if (!$store_name || !$city_id) $this->error('参数错误');
        $store = LihuaStore::where(['city_id'=> $city_id, 'name'=> $store_name])->find();
        $data['store']  = $store;
        $data['stocks'] = null;
        $data['city_id'] = $city_id;
        $citys = LihuaCity::where('id', $city_id)->field('name')->find();
        $data['city_name'] = $citys['name'];
        if ($store['id'] > 0) {
            $goods_ids  = LihuaGoods::where(['city_id' => $city_id, 'enable_stock' => 1])->column('id');
            if (!empty($goods_ids)) {
                $data['stocks'] = LihuaStock::whereIn('goods_id', $goods_ids)
                    ->where('store_id', $store['id'])
                    ->whereNotNull('num')
                    ->column('goods_id,num');
            }
        }
        $this->success('OK', $data);
    }

	/**
     * 商品结算
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求Token，游客不传")
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="store_id", type="int", required=true, description="门店ID")
     * @ApiParams   (name="goods_nums", type="string", required=true, description="商品ID及数量键值对JSON字符串")
     * @ApiParams   (name="platform", type="string", required=true, description="平台，默认为app")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573029992","data":{"useraddr":{"id":373694,"consignee":"吴大帝","mobile":"13961259811","address":"中吴大道777号308","name":"金龙大厦","house_num":"15幢37号"},"goods":[{"id":1180,"category_id":1,"name":"冬菇滑鸡饭","short_name":"冬菇滑鸡饭","description":"冬菇滑鸡 蒜泥毛白菜 五仁酱丁萝卜干送冰红茶（图片仅供参考）","pic":"https://lihua.czapi.cn/uploads/goods/2019/10/20725d9efea561b3e.jpg","price":0.01,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":1,"enable_stock":1,"num":2,"num_price":0.02},{"id":10015,"category_id":218,"name":"特别的爱砂锅","short_name":"特爱砂锅","description":"六荤六素全家福","pic":"http://image.lihua.com/images/newweb/2019/08/thumb_5d5b494cbe158.jpg","price":25,"box_fee":1,"limit_num":1,"at_least":1,"is_alone_sale":1,"enable_stock":1,"num":1,"num_price":25}],"goods_nums":{"1180":2,"10015":1},"goods_stocks":{"1180":5000,"10015":1000},"goods_amount":25.02,"packing_fee":1,"deliver_fee":3,"enough_fee":0,"original_amount":29.02,"order_amount":29.02,"discount":0}})
     */
    public function settle()
    {
        $this->request->filter('trim,strip_tags');
        $store_id       = (int)$this->request->post('store_id', 0);
        $goods_nums     = $this->request->post('goods_nums', '');
        $enterprise_id  = $this->request->post('enterprise_id', 0);//写字楼ID

        $api = "https://private.lihua.com/api/office/ent_info?enterprise_id=".$enterprise_id;
        $res = Http::get($api);
        $ret = json_decode($res, true);
        $data = $ret['data'];

        //首先判断是否已经过了截单时间
        $ent_ordering_time = json_decode($data['ordering_time'], true);
        $ent_stoptime = $ent_ordering_time[0]['stop'];
        if(date('H:i')>$ent_stoptime){
            // $this->error('该地点已过截止订餐时间，请选择其他订餐模式');
        }
        //判断菜单的正确性
        if (!$goods_nums) $this->error('请选择商品');
        $goods_nums = json_decode($goods_nums, true);
        if (!$goods_nums) $this->error('请选择商品');
        if (json_last_error()) $this->error('非法操作');
        $data = [];
        $user_id  = 0;
        if ($this->token) { $user_id  = (int)$this->auth->id; }
        
        //
        $goods = LihuaGoods::getOfficeCartGoodsList($store_id, $goods_nums, $user_id);
        if (!$goods['alone_sale']) $this->error('请选择一份主食，配餐商品单点不送');
        if ($goods['lack_goods']['ids']) $this->error(join('、', $goods['lack_goods']['names']) . ' 库存不足');
        $this->success('OK', $goods);
    }
	
    /**
     * 提交订单
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求Token，游客不传")
     * @ApiParams   (name="platform", type="string", required=true, description="平台，值为app或xcx")
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="pay_type", type="int", required=true, description="支付方式：1=支付宝支付，2=微信支付，3=丽华钱包，4=货到付款，5=贵宾卡支付")
     * @ApiParams   (name="addr_id", type="int", required=true, description="收货地址ID，会员必要")
     * @ApiParams   (name="consignee", type="string", required=true, description="收货人，游客必要")
     * @ApiParams   (name="mobile", type="string", required=true, description="收货手机，游客必要")
     * @ApiParams   (name="name", type="string", required=true, description="地址名称，游客必要")
     * @ApiParams   (name="house_num", type="string", required=true, description="地址门牌，游客必要")
     * @ApiParams   (name="lng", type="string", required=true, description="地址经度，游客必要")
     * @ApiParams   (name="lat", type="string", required=true, description="地址纬度，游客必要")
     * @ApiParams   (name="goods_nums", type="string", required=true, description="商品ID及数量键值对JSON字符串")
     * @ApiParams   (name="bonus_id", type="int", required=false, description="用户红包ID，默认0不使用红包")
     * @ApiParams   (name="deliver_time", type="string", required=true, description="送餐时间")
     * @ApiParams   (name="tableware", type="int", required=false, description="餐具：0=不需要，1=需要")
     * @ApiParams   (name="invo_id", type="int", required=false, description="发票ID，默认0不需要发票")
     * @ApiParams   (name="invo_type", type="int", required=false, description="发票类型，游客可传")
     * @ApiParams   (name="invo_title", type="string", required=false, description="发票抬头，游客可传")
     * @ApiParams   (name="taxno", type="string", required=false, description="发票税号，游客可传")
     * @ApiParams   (name="remark", type="string", required=false, description="订单备注")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1567010784","data":{"order_id":"1","sn":"190925460938715"}})
     */
    public function post()
    {
        $this->request->filter('trim,strip_tags');
        $goods_nums             = $this->request->post('goods_nums', '');           //商品及数量
        $address                = $this->request->post('address', '');              //地点详情
        $address_name           = $this->request->post('address_name', '');         //地址名称
        $address_id             = $this->request->post('address_id', 0);            //地址ID 来自私定系统
        $lat                    = $this->request->post('lat', '');                  //纬度
        $lng                    = $this->request->post('lng', '');                  //经度
        $enterprise_id          = $this->request->post('enterprise_id', 0);         //私定系统客户ID
        $office_setmeal_off     = $this->request->post('office_setmeal_off', '');   //套餐优惠折扣
        $office_single_off      = $this->request->post('office_single_off', '');    //单品优惠折扣
        $consignee              = $this->request->post('consignee', '');            //联系人
        $mobile                 = $this->request->post('mobile', '');               //联系电话
        $extra_attr             = $this->request->post('extra_attr', '');           //大楼扩展信息
        $remark                 = $this->request->post('remark', '');               //订单备注信息
        $arrive_time            = $this->request->post('arrive_time', '');          //送达时间
        $stop_time              = $this->request->post('stop_time', '');            //截止时间
        $store_id               = $this->request->post('store_id', 0);              //门店ID
        $city_id                = $this->request->post('city_id', 0);               //来源名称
        $platform               = $this->request->post('platform', 'xcx');          //来源名称
        
        if (!$address || !$address_name || !$address_id || 
            !$enterprise_id || !$lat || !$lng || !$consignee || !$mobile || 
            !$arrive_time || !$stop_time || !$store_id ) $this->error('非法操作');

        if (!$goods_nums)   $this->error('请选择商品');
        if (!$arrive_time) $this->error('请选择送餐时间');
        if (mb_strlen($remark) > 250) $this->error('订单备注请在250个字以内');
        //解析购物车信息
        $goods_nums = json_decode($goods_nums, true);
        //解析扩展信息
        $extra_attr_string = $extra_attr;
        $extra_attr = json_decode($extra_attr, true);
        if (json_last_error()) $this->error('商品数据异常');

        //判断登陆的情况
        if(!$this->token) $this->error('请先登录账号');
        //用户ID
        $user_id = $this->auth->id;
        
        //商品信息
        $goods = \app\common\model\goods\LihuaGoods::getOfficeCartGoodsList($store_id, $goods_nums, $user_id);
        if (!$goods['alone_sale']) $this->error('请选择一份主食，配餐商品单点不送');
        if ($goods['lack_goods']['ids']) $this->error(join('、', $goods['lack_goods']['names']) . ' 库存不足');


        //获取门店信息
        $store = LihuaStore::where(['id'=> $store_id])->find();
        //获取城市信息
        $city_name = LihuaCity::where(['id'=>$city_id])->column("name");
        $city_name = $city_name[0];
        //获取商品ID列表
        $goods_ids = array_keys($goods_nums);
        $good_lists = collection(LihuaGoods::whereIn('id', $goods_ids)->select())->toArray();
        $goods_map = [];
        foreach ($good_lists as $k => $v) {
            $office_price = 0;
            if(!!$v['is_alone_sale']){
                $office_price = round(((float)$v['price'] * (float)$office_setmeal_off) / 10, 2);
            }else{
                $office_price = round(((float)$v['price'] * (float)$office_single_off) / 10, 2);
            }
            $v['office_price'] = (float)$office_price;
            $v['off_price'] = bcsub($v['price'], (float)$office_price, 2);//优惠金额
            $good_lists[$k]['off_price'] = $v['off_price'];
            $goods_map[$v['id']] = $v;
        }
        $order_data = [];
        $order_amount = $goods_amount = $original_amount = 0; //订单需要支付的金额
        $order_discount = 0; //订单优惠金额
        // 计算商品的价格,和优惠总价
        foreach ($goods_nums as $goodid => $nums) {
            $office_price = $goods_map[$goodid]['office_price'];
            $good_price = $goods_map[$goodid]['price'];
            $order_amount = bcadd($order_amount, (float)round($office_price * $nums, 2), 2);
            $off_price = $goods_map[$goodid]['off_price'];
            $order_discount = bcadd($order_discount, (float)round($off_price * $nums, 2), 2);
            $goods_amount = bcadd($goods_amount, (float)round($good_price * $nums, 2), 2);
        }
        //订单号
        $sn = date('ym') . sprintf("%05d", mt_rand(1, 99999)) . date('d') . sprintf("%05d", mt_rand(1, 99999));
        /**
         * 不能使用红包
         * 不能使用现金抵用券
         * 不能使用VIP支付
         * 不能使用货到付款
         * **/
        $order_amount = bcadd($order_amount, (float)$goods['packing_fee'], 2);
        if ($order_amount == 0) $this->error('生成订单异常，请重试');
        //订单数据
        $data = [
            'sn'                => $sn,
            'user_id'           => $user_id,
            'city_id'           => $city_id,
            'city_name'         => $city_name,
            'store_id'          => $store_id,
            'store_name'        => $store['name'],
            'consignee'         => $consignee,
            'mobile'            => $mobile,
            'address'           => $address.' '.$extra_attr['room'] . "室",
            'lng'               => $lng,
            'lat'               => $lat,
            'deliver_time'      => date('Y-m-d ') . $arrive_time . ':00',
            'remark'            => $remark,//备注
            'goods_amount'      => $goods_amount,
            'original_amount'   => $goods_amount,//商品费+餐盒费+送餐费
            'order_amount'      => $order_amount,//商品费+餐盒费+送餐费-满减费-红包费
            'discount'          => $order_discount,//满减费+红包费
            'platform'          => $platform,
            'add_time'          => date('Y-m-d H:i:s'),
            'status'            => 1,//1待支付
            'office_id'         => $address_id,//写字楼用餐对应的客户id
            'office_stoptime'   => date('Y-m-d ') . $stop_time . ':00',
            'office_extra_attr' => $extra_attr_string,
            'packing_fee'       => $goods['packing_fee'],
        ];
        //创建订单
        $order_id = 0;
        Db::startTrans();
        try {
            $order = LihuaOrder::create($data);
            Db::commit();
            $order_id = $order->id;
        } catch (Exception $e) {
            Db::rollback();
            $this->error('提交失败，请尝试重新提交');
        }
        //商品减库存
        if ($goods['goods_stocks']) {
            foreach ($goods_nums as $k => $v) {
                if (isset($goods['goods_stocks'][$k])) {
                    LihuaStock::where(['goods_id' => $k, 'store_id' => $store_id])->setDec('num', $v);
                }
            }
        }

        //保存商品信息
        $orderGoods = [];
        //这里需要判断如果没有餐盒费

        foreach ($good_lists as $k => $v) {
            $num = $goods_nums[$v['id']];
            $num_price = (float)round($v['off_price'] * $num, 2);

            if(substr($v['pic'], 0, 4)=='http'){
                $pic_url = $v['pic'];
            }else{
                $pic_url = "https://newapp.lihua.com".$v['pic'];
            }

            $orderGoods[] = [
                'order_id'    => $order_id,
                'order_sn'    => $sn,
                'city_id'     => $city_id,
                'store_id'    => $store_id,
                'user_id'     => $user_id,
                'goods_id'    => $v['id'],
                'name'        => $v['name'],
                'short_name'  => $v['short_name'],
                'description' => $v['description'],
                'price'       => $v['price'],
                'pic'         => $pic_url,
                'num'         => $num,
                'num_price'   => $num_price,
                'box_fee'     => (float)round($v['box_fee'] * $num, 2),
                'create_date' => date('Y-m-d'),
            ];
        }
        if ($orderGoods) LihuaOrderGoods::insertAll($orderGoods);
        $this->success('OK', ['order_id' => $order_id, 'sn' => $sn]);
    }

    /**
     * 更具订单sn获取订单商品列表
     * **/
    public function getordergoods(){
        $sn = $this->request->request('sn', '');//订单sn
        if ( !$sn ) $this->error('参数错误');
        $list = LihuaOrderGoods::where(['order_sn'=> $sn])->select();
        $this->success('OK', $list);
    }

    /***
     * 同步订单到私定系统接口
     * 此处需要提供订单详情
     * 和订单商品列表
     * 只能同步当天的订单
     * ***/
    public function getordertoprivate()
    {
        $where = [
            'office_id'=> ['>', 0],//写字楼ID不能为0
            'status' => 2, //订单状态是已支付的订单
            'office_status' => 0, //查询还没有被同步过的订单
        ];
        $list = LihuaOrder::where($where)->limit(50)->select();
        $order_list = $this->reOrderList($list);
        $this->success('OK', $order_list);
    }

    /**
     * 重新组织订单列表数据
     *
     * @ApiInternal
     * @param array $list 订单列表
     * @return array
     */
    public function reOrderList($list = [])
    {
        $data = [];
        if ($list) {
            $ids    = array_column($list, 'id');
            $goods  = LihuaOrderGoods::ordersGoodsList($ids);
            $status = LihuaOrder::getStatusList();
            foreach ($list as $k => $v) {
                $data[] = [
                    'id'                    => $v['id'],
                    'sn'                    => $v['sn'],
                    'time'                  => date("Y-m-d H:i", $v['create_time']),
                    'status'                => $v['status'],
                    'status_text'           => isset($status[$v['status']]) ? $status[$v['status']] : '',
                    'goods'                 => isset($goods[$v['id']]) ? $goods[$v['id']] : [],
                    'discount'              => round($v['discount'], 2),
                    'amount'                => round($v['order_amount'], 2),
                    'goods_amount'          => round($v['goods_amount'], 2),
                    'doorshop'              => isset($v['doorshop']) ? $v['doorshop'] : 0,
                    'office_id'             => $v['office_id'],//对应客户ID
                    'wallet_given_fee'      => isset($v['wallet_given_fee']) ? $v['wallet_given_fee'] : 0,//钱包赠送金额支付
                    "office_stoptime"       => $v['office_stoptime'],
                    "office_status"         => $v['office_status'],
                    'wallet_random_fee'     => $v['wallet_random_fee'],//钱包随机立减
                    'remark'                => $v['remark'],
                    'deliver_time'          => $v['deliver_time'],
                    'consignee'             => $v['consignee'],
                    'mobile'                => $v['mobile'],
                    'pay_type'              => $v['pay_type'],
                    'office_extra_attr'     => $v['office_extra_attr'],
                    'packing_fee'           => $v['packing_fee'],
                ];
            }
        }
        return $data;
    }

    /***
     * 更新写字楼订单同步状态
     * ***/
    public function changeorder_office_status()
    {
        $sn = $this->request->request('sn', '');//订单sn
        if ( !$sn ) $this->error('参数错误');
        $row = LihuaOrder::getBySn($sn);
        //状态：0=取消订单，3=确认订单，4=分配门店，5=骑手配送，6=订单完成
        //只有订单状态在2的情况下才需要更新状态x
        if (!$row) $this->error($sn . ' 订单不存在');
        if ($row->status != 2) $this->error($sn . '订单状态无需更新');
        $row->status = 3;
        $row->confirm_time = date('Y-m-d H:i:s');
        $row->update_time = date('Y-m-d H:i:s');
        $row->save();
        LihuaOrderLogistics::create([
            'order_id' => $row['id'],
            'order_sn' => $sn,
            'des'      => '订单已经分配，等待派送',
            'status'   => $row->status,
        ]);
        $this->success('OK', $sn);
    }
}